<template>
    <div class="storage-test">
        <h2>StorageUtils 手机环境测试</h2>

        <div class="test-section">
            <h3>基本功能测试</h3>
            <button @click="testBasicStorage">测试基本存储</button>
            <button @click="testComplexData">测试复杂数据</button>
            <button @click="testCounter">测试计数器</button>
            <button @click="clearAllData">清空所有数据</button>
        </div>

        <div class="test-section">
            <h3>环境检测</h3>
            <div class="env-info">
                <p>当前环境: {{ currentEnv }}</p>
                <p>HTML5+ 可用: {{ plusAvailable ? '是' : '否' }}</p>
                <p>localStorage 可用: {{ localStorageAvailable ? '是' : '否' }}</p>
                <p>sessionStorage 可用: {{ sessionStorageAvailable ? '是' : '否' }}</p>
            </div>
        </div>

        <div class="test-section">
            <h3>存储数据</h3>
            <div class="data-display">
                <p>用户ID: {{ storedData.userId || '未设置' }}</p>
                <p>用户名: {{ storedData.userName || '未设置' }}</p>
                <p>访问次数: {{ storedData.visitCount || 0 }}</p>
                <p>最后访问: {{ storedData.lastVisit || '未设置' }}</p>
                <p>用户偏好: {{ JSON.stringify(storedData.preferences) || '未设置' }}</p>
            </div>
        </div>

        <div class="test-section">
            <h3>操作日志</h3>
            <div class="log-container">
                <div v-for="(log, index) in logs" :key="index" class="log-item">
                    <span class="log-time">{{ log.time }}</span>
                    <span class="log-message">{{ log.message }}</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { StorageUtils } from '@/utils/storage.js'

const currentEnv = ref('检测中...')
const plusAvailable = ref(false)
const localStorageAvailable = ref(false)
const sessionStorageAvailable = ref(false)
const logs = ref([])
const storedData = ref({})

// 添加日志
const addLog = (message) => {
    const time = new Date().toLocaleTimeString()
    logs.value.unshift({ time, message })
    if (logs.value.length > 10) {
        logs.value = logs.value.slice(0, 10)
    }
}

// 检测环境
const detectEnvironment = () => {
    // 检测 HTML5+
    if (typeof window !== 'undefined' && window.plus) {
        plusAvailable.value = true
        currentEnv.value = 'HTML5+ 环境'
        addLog('检测到 HTML5+ 环境')
    } else if (typeof uni !== 'undefined') {
        currentEnv.value = 'uni-app 环境'
        addLog('检测到 uni-app 环境')
    } else if (typeof window !== 'undefined') {
        currentEnv.value = '浏览器环境'
        addLog('检测到浏览器环境')
    } else {
        currentEnv.value = '未知环境'
        addLog('未知环境')
    }

    // 检测 localStorage
    try {
        localStorage.setItem('test', 'test')
        localStorage.removeItem('test')
        localStorageAvailable.value = true
        addLog('localStorage 可用')
    } catch (e) {
        localStorageAvailable.value = false
        addLog('localStorage 不可用')
    }

    // 检测 sessionStorage
    try {
        sessionStorage.setItem('test', 'test')
        sessionStorage.removeItem('test')
        sessionStorageAvailable.value = true
        addLog('sessionStorage 可用')
    } catch (e) {
        sessionStorageAvailable.value = false
        addLog('sessionStorage 不可用')
    }
}

// 测试基本存储
const testBasicStorage = () => {
    try {
        // 保存基本数据
        StorageUtils.setData('test_user_id', '12345')
        StorageUtils.setData('test_user_name', '测试用户')
        StorageUtils.setData('test_boolean', true)
        StorageUtils.setData('test_number', 42)

        // 读取数据
        const userId = StorageUtils.getData('test_user_id', '')
        const userName = StorageUtils.getData('test_user_name', '')
        const testBoolean = StorageUtils.getData('test_boolean', false)
        const testNumber = StorageUtils.getData('test_number', 0)

        addLog(`基本存储测试成功: ${userId}, ${userName}, ${testBoolean}, ${testNumber}`)

        // 更新显示数据
        storedData.value.userId = userId
        storedData.value.userName = userName

    } catch (e) {
        addLog(`基本存储测试失败: ${e.message}`)
    }
}

// 测试复杂数据
const testComplexData = () => {
    try {
        const complexData = {
            user: {
                id: '12345',
                name: '张三',
                email: 'zhangsan@example.com'
            },
            preferences: {
                theme: 'dark',
                language: 'zh-CN',
                notifications: true
            },
            settings: {
                autoSave: true,
                syncInterval: 300
            }
        }

        StorageUtils.setData('test_complex_data', complexData)
        const retrievedData = StorageUtils.getData('test_complex_data', null)

        if (retrievedData && retrievedData.user.name === '张三') {
            addLog('复杂数据存储测试成功')
            storedData.value.preferences = retrievedData.preferences
        } else {
            addLog('复杂数据存储测试失败')
        }

    } catch (e) {
        addLog(`复杂数据测试失败: ${e.message}`)
    }
}

// 测试计数器
const testCounter = () => {
    try {
        const currentCount = StorageUtils.getData('test_visit_count', 0)
        const newCount = currentCount + 1
        StorageUtils.setData('test_visit_count', newCount)

        addLog(`计数器测试: ${currentCount} -> ${newCount}`)
        storedData.value.visitCount = newCount

    } catch (e) {
        addLog(`计数器测试失败: ${e.message}`)
    }
}

// 清空所有数据
const clearAllData = () => {
    try {
        StorageUtils.clearAllData()
        addLog('所有数据已清空')
        storedData.value = {}
    } catch (e) {
        addLog(`清空数据失败: ${e.message}`)
    }
}

// 加载已存储的数据
const loadStoredData = () => {
    try {
        storedData.value = {
            userId: StorageUtils.getData('test_user_id', ''),
            userName: StorageUtils.getData('test_user_name', ''),
            visitCount: StorageUtils.getData('test_visit_count', 0),
            lastVisit: StorageUtils.getData('test_last_visit', ''),
            preferences: StorageUtils.getData('test_complex_data', {}).preferences || {}
        }
        addLog('已加载存储的数据')
    } catch (e) {
        addLog(`加载数据失败: ${e.message}`)
    }
}

onMounted(() => {
    detectEnvironment()
    loadStoredData()

    // 记录访问时间
    StorageUtils.setData('test_last_visit', new Date().toLocaleString())
    storedData.value.lastVisit = new Date().toLocaleString()
})
</script>

<style scoped>
.storage-test {
    padding: 20px;
    max-width: 600px;
    margin: 0 auto;
}

.test-section {
    margin-bottom: 30px;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
}

.test-section h3 {
    margin-top: 0;
    color: #333;
}

button {
    margin: 5px;
    padding: 8px 16px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

.env-info {
    background-color: #f8f9fa;
    padding: 10px;
    border-radius: 4px;
}

.env-info p {
    margin: 5px 0;
    font-family: monospace;
}

.data-display {
    background-color: #e9ecef;
    padding: 10px;
    border-radius: 4px;
}

.data-display p {
    margin: 5px 0;
    font-family: monospace;
}

.log-container {
    max-height: 200px;
    overflow-y: auto;
    background-color: #f8f9fa;
    padding: 10px;
    border-radius: 4px;
}

.log-item {
    margin: 5px 0;
    font-family: monospace;
    font-size: 12px;
}

.log-time {
    color: #666;
    margin-right: 10px;
}

.log-message {
    color: #333;
}
</style>

